#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h>
#include <string>
#include <iostream>

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    //int data_size = 1024*10000;
    //char buffer[data_size];
    std::string message;


    time_t seconds;
    time(&seconds);
    srand((unsigned int) seconds);

    if (argc < 3)
    {
       fprintf(stderr,"usage %s hostname port\n", argv[0]);
       exit(0);
    }

    portno = atoi(argv[2]);
    //message = argv[3];
    std::cin >> message;

    int data_size = message.length() + 100; //1024*10000;
    char buffer[data_size];

    printf("%i\n", data_size);


    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = PF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);

    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
    	error("ERROR connecting");

    while(true)
    {
    	bzero(buffer, data_size);
    	strcpy(buffer, message.c_str());

    	if((n = send(sockfd, buffer, message.length(), 0)) < 0)
    	{
    		close(sockfd);
    		error("Can't send");
    	}

    	if((n = recv(sockfd, buffer, data_size, 0)) < 0)
    	{
    		close(sockfd);
    		error("Can't receive\n");
    	}

    	buffer[n-1] = '\0';
    	if(strcmp(buffer, "Get off!") == 0)
    	{
    		close(sockfd);
    		break;
    	}
    }

    close(sockfd);

    return 0;
}
